package com.efounder.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilemall.R;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.mobilemallpay.pays.WxPay;

import java.util.HashMap;

/**
 * Created by will on 18-2-8.
 * 支付时弹出activity，上部透明
 * @author will
 */

public class MallCheckoutActivity extends Activity implements View.OnClickListener{

    View rootView;
    TextView tvTimeLeft, tvCheckoutPrice;
    ImageView ivAliPay, ivWXPay;
    LinearLayout llAliPay, llWXPay;
    private String payType = "ali";
    private String orderId, orderAmount, orderTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_checkout);
        Bundle bundle = getIntent().getExtras();
        orderId = bundle.getString("orderId");
        orderAmount = bundle.getString("orderAmount");
        orderTitle = bundle.getString("orderTitle");
        initView();
    }

    public void initView() {
        rootView = (View) findViewById(R.id.root_view);
        View transparentView = (View) findViewById(R.id.transparent_view);
        transparentView.setOnClickListener(this);
        ImageView ivClose = (ImageView) findViewById(R.id.iv_close);
        ivClose.setOnClickListener(this);
        TextView tvCheckout = (TextView) findViewById(R.id.tv_checkout);
        tvCheckout.setOnClickListener(this);
        tvTimeLeft = (TextView) findViewById(R.id.tv_checkout_time_left);
        tvCheckoutPrice = (TextView) findViewById(R.id.tv_checkout_price);
        tvCheckoutPrice.setText(orderAmount);
        llAliPay = (LinearLayout) findViewById(R.id.alicheckBtn);
        llAliPay.setOnClickListener(this);
        llWXPay = (LinearLayout) findViewById(R.id.wxcheckBtn);
        llWXPay.setOnClickListener(this);
        ivAliPay = (ImageView) findViewById(R.id.alicheckImage);
        ivWXPay = (ImageView) findViewById(R.id.wxcheckImage);
    }

    @Override
    public void finish() {
        super.finish();
        this.overridePendingTransition(R.anim.bottom_dialog_exit,0);
    }

    @Override
    public void onBackPressed() {
        abortCheckoutAlert();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.transparent_view || id == R.id.iv_close) {
            abortCheckoutAlert();
        } else if (id == R.id.alicheckBtn) {
            llAliPay.setBackgroundColor(getResources().getColor(R.color.colorGrayBg));
            llWXPay.setBackgroundColor(getResources().getColor(R.color.white));
            ivAliPay.setVisibility(View.VISIBLE);
            ivWXPay.setVisibility(View.INVISIBLE);
            payType = "ali";
        } else if (id == R.id.wxcheckBtn) {
            llAliPay.setBackgroundColor(getResources().getColor(R.color.white));
            llWXPay.setBackgroundColor(getResources().getColor(R.color.colorGrayBg));
            ivAliPay.setVisibility(View.INVISIBLE);
            ivWXPay.setVisibility(View.VISIBLE);
            payType = "wx";
        } else if (id == R.id.tv_checkout) {
            pay(payType);
        }
    }

    private void pay(String type) {
//        if (mOrderBean == null) {
//            ToastUtil.showToast(this, "订单为空");
//            return;
//        }
        HashMap<String, String> orderBeanMap = new HashMap<>();
        //请求订单号
        PayInter pay = null;
        if ("wx".equals(type)) {
            //wx支付
            pay = new WxPay(this);
        } else {
            pay = new AliPay(this);
        }
        orderBeanMap.put("paytype", payType);
        orderBeanMap.put("method", "payOrder");
        orderBeanMap.put("appbh", "zx");
        orderBeanMap.put("orderid", orderId);
        //监听页面
        listenerActivityNotifycation();

        String url = EnvironmentVariable.getProperty("videoURL") + "/PayService";
        pay.setURLAndParams(url, orderBeanMap);

        //无法直接向wxpayentryactivity传值,如果支付方式是微信的话,醉了醉了;
        EnvironmentVariable.setProperty("mobile_pay_good_name", ResStringUtil.getString(R.string.mail_mall_self_support));
        EnvironmentVariable.setProperty("mobile_pay_good_description", orderTitle);
        EnvironmentVariable.setProperty("mobile_pay_good_price", orderAmount);
        final PayInter finalPay = pay;
        pay.pay(new OnPayListener() {
            @Override
            public void onPaySuccess() {
                ToastUtil.showToast(MallCheckoutActivity.this,ResStringUtil.getString(R.string.mail_pay_success));
                if (finalPay instanceof AliPay) {
                    //阿里支付成功后需要手动跳转到支付成功界面
                    //微信会自动跳转到成功界面;
                    Intent intent = new Intent(MallCheckoutActivity.this, WXPayEntryActivity.class);
                    intent.putExtra("type", "ali");
                    intent.putExtra("status", "success");
                    startActivity(intent);
                }
            }

            @Override
            public void onPayFailure(String msg, int code) {
                if (code == OnPayListener.ERROR) {
                    ToastUtil.showToast(MallCheckoutActivity.this, msg);
                    if (finalPay instanceof AliPay) {
                        //阿里支付成功后需要手动跳转到支付成功界面
                        //微信会自动跳转到成功界面;
                        Intent intent = new Intent(MallCheckoutActivity.this, WXPayEntryActivity.class);
                        intent.putExtra("type", "ali");
                        intent.putExtra("status", "failure");
                        startActivity(intent);
                    }
                }
            }
        });
    }

    private void listenerActivityNotifycation() {
        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(MallCheckoutActivity.this).unregisterReceiver(this);
                finish();
            }
        }, new IntentFilter(WXPayEntryActivity.FINISH_ORDER_ACTIVITY));
    }

    private void abortCheckoutAlert() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_abort_checkout, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        final PopupWindow abortAlert = new PopupWindow(contentView,
                screenWidth / 6 * 5, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TextView tvAbort = (TextView) contentView.findViewById(R.id.tv_abort_checkout);
        TextView tvResume = (TextView) contentView.findViewById(R.id.tv_resume_checkout);
        tvAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                abortAlert.dismiss();
                finish();
            }
        });
        tvResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                abortAlert.dismiss();
            }
        });
        abortAlert.setContentView(contentView);
        abortAlert.setFocusable(true);
        abortAlert.setBackgroundDrawable(new BitmapDrawable());
        abortAlert.setOutsideTouchable(false);
        abortAlert.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }

}
